
importClass('java.io.FileOutputStream');
importClass('java.io.IOException');
importClass('java.io.InputStream');
importClass('java.net.MalformedURLException');
importClass('java.net.URL');
importClass('java.net.URLConnection');
importClass('java.util.ArrayList');

/**
 * true：是调试模式
 * false：是发布模式
 */
var is_debug = false;

/**
 * 最基础的网址
 */
const SERVER_BASE_ADDR = "http://server.wzdy.fkapp.top:38886";
const SERVER_BASE_POINT = "38886";
const SCRIPT_DIR = "RabbitScript";

/**
 * 1、检查本地存放的脚本信息，版本号
 * 2、检查本地是否有脚本
 * 3、如果没有脚本就从服务器获取脚本
 * 4、从服务器下载脚本
 * 5、运行本地脚本
 */

 var storage;
 var version_app;
 var version_latest_script;
 var version_old_script;
 var script_addr;
 var phoneCard;
 var server_addr;
 var addr_base_cwd;

function main() {
    storage = storages.create("rabbit:info");
    version_app = storage.get('version_app', '0');
    version_latest_script = storage.get('version_latest_script', '0');
    version_old_script = storage.get('version_old_script', '0');
    script_addr = storage.get('script_addr', '0');
    phoneCard = storage.get('phoneCard', '0');
    server_addr = storage.get('server_addr', SERVER_BASE_ADDR);
    addr_base_cwd = storage.get('addr_base_cwd', '0');
    // var phoneCard = storage.get('phoneCard', '0');
    console.log("version_app:", version_app);
    console.log("version_latest_script:", version_latest_script);
    console.log("version_old_script:", version_old_script);
    console.log("script_addr:", script_addr);
    console.log("phoneCard:", phoneCard);
    console.log("server_addr:", server_addr);
    console.log("addr_base_cwd:", addr_base_cwd);

    if (addr_base_cwd == 0) {
        storage.put('addr_base_cwd', engines.myEngine().cwd());
    }

    if (files.create(files.getSdcardPath() + "/" + SCRIPT_DIR + "/")) {
        console.log("脚本文件夹 RabbitScript 创建成功");
        version_latest_script = "0";
    } else {
        console.log("脚本文件夹 RabbitScript 已存在");
    }
    if (files.create(files.getSdcardPath() + "/RabbitConf/")) {
        console.log("脚本文件夹 RabbitConf 创建成功");
    } else {
        console.log("脚本文件夹 RabbitConf 已存在");
    }
    if (files.create(files.getSdcardPath() + "/RabbitLog/")) {
        console.log("脚本文件夹 RabbitLog 创建成功");
    } else {
        console.log("脚本文件夹 RabbitLog 已存在");
    }

    if (version_latest_script == "0" || script_addr == "0" ) {
        toastLog("需要从服务器下载最新的脚本文件!!!");
        if (!GetVersion()) {
            toastLog("从服务器获取脚本文件失败，请联系作者!!!");
            return;
        };
        console.log(script_addr);

        // 遍历脚本路径
        for (var key in script_addr) {
            console.log("key:", key);
            var s_url = server_addr + "/apps/script/" + version_latest_script + script_addr[key] + key;
            var s_folder_path = files.getSdcardPath()+"/" + SCRIPT_DIR + "/" + version_latest_script + script_addr[key];
            var s_file_path = s_folder_path + key;

            files.createWithDirs(s_folder_path);

            console.log("s_url:", s_url);
            console.log("s_file_path:", s_file_path);
            download(s_url, s_file_path);
        }

    } else {
        console.log("检测到有脚本版本号");
        var script_chack_addr = files.getSdcardPath() + "/" + SCRIPT_DIR + "/" + version_latest_script + "/";
        var b_check_script_dir = files.createWithDirs(script_chack_addr);
        if (b_check_script_dir) {
            console.log("当前使用脚本文件夹 不存在 需要重新下载脚本文件");
            // 遍历脚本路径
            for (var key in script_addr) {
                console.log("key:", key);
                var s_url = server_addr + "/apps/script/" + version_latest_script + script_addr[key] + key;
                var s_folder_path = files.getSdcardPath()+"/" + SCRIPT_DIR + "/" + version_latest_script + script_addr[key];
                var s_file_path = s_folder_path + key;

                files.createWithDirs(s_folder_path);

                console.log("s_url:", s_url);
                console.log("s_file_path:", s_file_path);
                download(s_url, s_file_path);
            }
        } else {
            console.log("对脚本文件进行校验，如果没有脚本则重新下载");

            // 遍历脚本路径
            for (var key in script_addr) {
                console.log("key:", key);
                var s_url = server_addr + "/apps/script/" + version_latest_script + script_addr[key] + key;
                var s_folder_path = files.getSdcardPath()+"/" + SCRIPT_DIR + "/" + version_latest_script + script_addr[key];
                var s_file_path = s_folder_path + key;
                if (!files.isFile(s_file_path)) {
                    files.createWithDirs(s_folder_path);

                    console.log("s_url:", s_url);
                    console.log("s_file_path:", s_file_path);
                    download(s_url, s_file_path);                   
                }
            }
        }
    }

    console.log("检测脚本没有问题，运行脚本。");
    var script_dir = "";
    if (is_debug) {
        script_dir = engines.myEngine().cwd() + "/" + version_latest_script + "/";
    } else {
        script_dir = files.getSdcardPath() + "/" + SCRIPT_DIR + "/" + version_latest_script + "/"
    }

    engines.execScriptFile((script_dir + "main.js"),{
        path: script_dir
    }); 
}

/**
 * 
 * @returns true: 获取版本信息成功，false：获取版本信息错误
 */
function GetVersion() {
    console.log("in GetAppVersion");
    var ret = false;
    var hGet = http.get(server_addr + "/api/GetScriptLatestVersion/");

    if (hGet.statusCode == 200) {
        console.log("获取成功");
        retjs = hGet.body.json();
        console.log("cmd:", retjs["cmd"]);
        console.log("latest_version:", retjs["script"]["latest_version"]);
        console.log("script_dirs:", retjs["script"]["script_dirs"]);
        console.log("Script_Base:", retjs["script"]["script_dirs"]["Script_Base.js"]);
        console.log("获取完成");

        if (retjs["script"]["latest_version"] != version_latest_script) {
            version_old_script = version_latest_script;
            storage.put('version_old_script', version_old_script);
        }

        version_latest_script = retjs["script"]["latest_version"];
        storage.put('version_latest_script', version_latest_script);

        script_addr = retjs["script"]["script_dirs"];
        storage.put('script_addr', script_addr);
        ret = true;
    } else {
        toastLog("向服务器请求新脚本出现错误！！！");
    }
    console.log("out GetAppVersion");
    return ret;
}

/**
 * 初始化控制台
 */
function initConsole(){
    var log_file = files.getSdcardPath() + "/RabbitLog/" + "1.txt";
    console.setGlobalLogConfig({
        "file": log_file,
    });
}

/**
 * 将服务器上的脚本下载到本地。
 * @param {string} url 下载地址
 * @param {string} filePath 本地保存地址
 */
function download(url, filePath) {
    var url = new URL(url);
    var conn = url.openConnection(); //URLConnection
    var inStream = conn.getInputStream(); //InputStream
    var fs = new FileOutputStream(filePath); //FileOutputStream
    var connLength = conn.getContentLength(); //int
    var buffer = util.java.array('byte', 1024); //byte[]
    var byteSum = 0; //总共读取的文件大小
    var byteRead; //每次读取的byte数
    log('要下载的文件大小=', connLength);
    var threadId = threads.start(function() {
        let nowDate = new Date();
        while (new Date() - nowDate < 1000 * 10) {
            var 当前写入的文件大小 = byteSum;
            var progress = (当前写入的文件大小 / connLength) * 100;
            if (progress > 0.1) {
                var progress = parseInt(progress).toString() + '%';
                if (当前写入的文件大小 >= connLength) {
                    break;
                }
            }
            sleep(1000);
        }
    });
    while ((byteRead = inStream.read(buffer)) != -1) {
        byteSum += byteRead;
        //当前时间
        currentTime = java.lang.System.currentTimeMillis();
        fs.write(buffer, 0, byteRead); //读取
    }
    threadId && threadId.isAlive() && threadId.interrupt();
    console.log('下载完成');
}

threads.start(function (){
    initConsole();
    main();
}); 